package com.only4play.authcenter.infrastructure.security.providers.admin.password;

import com.only4play.authcenter.domain.adminaccount.service.IAdminAccountService;
import com.only4play.authcenter.infrastructure.security.providers.exception.BlackListException;
import com.only4play.authcenter.infrastructure.security.providers.model.LoginSuccessToken;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collections;
import java.util.UUID;

/**
 * @author hinzzz www.hinzzz.cn 157957329@qq.com
 * 2024-03-05
 */
@Slf4j
@RequiredArgsConstructor
public class PasswordProviders implements AuthenticationProvider {

    private final IAdminAccountService adminAccountService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        PasswordToken passwordToken = (PasswordToken) authentication;
        log.info("密码登录逻辑开始");
        log.info("用户名：{} 密码{}", passwordToken.getUsername(), passwordToken.getPassword());

        LoginSuccessToken successToken = new LoginSuccessToken(Collections.emptyList());
        //校验用户名密码
        if ("hinzzz".equals(passwordToken.getUsername()) && "123456".equals(passwordToken.getPassword())) {
            successToken.setUsername("hinzzz");
            successToken.setLastLoginTime(System.currentTimeMillis());
            successToken.setToken(UUID.randomUUID().toString());
        } else {
            throw new BlackListException("黑名单");
        }
        SecurityContextHolder.getContext().setAuthentication(successToken);
        return successToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.isAssignableFrom(PasswordToken.class);
    }
}
